package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.JgLowDialog;
import com.asktgapp.eventbus.PayFinishEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.FreeAskSearchVO;
import com.asktgapp.model.LawVO;
import com.asktgapp.model.NewEngineerDetailVO;
import com.asktgapp.model.NewHomeTwoBean;
import com.asktgapp.model.RewardBean;
import com.asktgapp.model.UserInfoVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.NewWebActivity;
import com.asktgapp.user.activity.PayActivity;
import com.asktgapp.user.activity.UsedCheckActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.LabelLayout;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 2018年7月31日 10:25:50
 * Description: 快速付款输入金额页面
 */

public class FastPaymentFragment extends BaseFragment {

    @InjectView(R.id.myBack)
    TextView myBack;
    @InjectView(R.id.myToolbarRight)
    TextView myToolbarRight;
    @InjectView(R.id.userHead)
    ImageView userHead;
    @InjectView(R.id.payName)
    TextView payName;
    @InjectView(R.id.payPhone)
    TextView payPhone;

    @InjectView(R.id.payNumber)
    EditText payNumber;

    @InjectView(R.id.receivablesHead)
    ImageView receivablesHead;
    @InjectView(R.id.receivablesName)
    TextView receivablesName;
    @InjectView(R.id.receivablesType)
    TextView receivablesType;
    @InjectView(R.id.receivablesType2)
    TextView receivablesType2;

    @InjectView(R.id.payPurposes)
    LabelLayout payPurposes;
    @InjectView(R.id.etPurposes)
    EditText etPurposes;

    @InjectView(R.id.cbLaw)
    CheckBox cbLaw;
    @InjectView(R.id.tvLawMZ)
    TextView tvLawMZ;
    @InjectView(R.id.commitPay)
    TextView commitPay;
    @InjectView(R.id.rvPayUser)
    RecyclerView rvPayUser;
    private boolean isReward = false, otherRemarks = false;
    private Set<String> typeSet;
    private String receivablesUserId, receivablesHeadUrl;
    private BaseAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_fast_payment, container, false);
        ButterKnife.inject(this, viewGroup);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        isReward = getActivity().getIntent().getBooleanExtra("isReward", false);
        FreeAskSearchVO.AnswerListBean answerListBean = (FreeAskSearchVO.AnswerListBean) getActivity().getIntent().getSerializableExtra("receivables");
        if (answerListBean == null)
            return;
        receivablesName.setText(answerListBean.getUsername1());
        ImageDisplayUtil.loadCircleHeadImage(getActivity(), receivablesHead, answerListBean.getUserPic1());
        receivablesHeadUrl = answerListBean.getUserPic1();
        receivablesUserId = answerListBean.getAuserId();
        if (isReward) {
            etPurposes.setVisibility(View.GONE);
            tvLawMZ.setText("《打赏协议》");
            rvPayUser.setVisibility(View.VISIBLE);
            rvPayUser.setNestedScrollingEnabled(false);
            rvPayUser.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        } else {
            rvPayUser.setVisibility(View.GONE);
            tvLawMZ.setText("《快捷支付协议》");
        }
        getBaseActivity().getToolbar().setVisibility(View.GONE);

        String label = getBaseActivity().getIntent().getStringExtra("label");
        if (!TextUtils.isEmpty(label)) {
            String[] str = label.split(",");
            if (str.length == 0) {
                receivablesType.setVisibility(View.GONE);
                receivablesType2.setVisibility(View.GONE);
            } else if (str.length == 1) {
                if (Util.isEmpty(str[0])) {
                    receivablesType.setVisibility(View.GONE);
                } else {
                    receivablesType.setVisibility(View.VISIBLE);
                }
                receivablesType2.setVisibility(View.GONE);
                receivablesType.setText(str[0]);
            } else if (str.length >= 2) {
                receivablesType.setVisibility(View.VISIBLE);
                receivablesType2.setVisibility(View.VISIBLE);
                receivablesType.setText(str[0]);
                receivablesType2.setText(str[1]);
            }
        } else {
            receivablesType.setVisibility(View.GONE);
            receivablesType2.setVisibility(View.GONE);
        }
        typeSet = new HashSet<>();

        myBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBaseActivity().onBackPressed();
            }
        });

        tvLawMZ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMZ == null) {
                    mMZ = new LawVO();
                }
                String title;
                if (isReward)
                    title = "打赏协议";
                else
                    title = "快捷支付协议";
                JgLowDialog jgLowDialog1 = new JgLowDialog(title, mMZ.getContent());
                jgLowDialog1.show(getFragmentManager(), "JgLowDialog1");
            }
        });

        myToolbarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewEngineerDetailVO bean = (NewEngineerDetailVO) getBaseActivity().getIntent().getSerializableExtra("bean");
                Intent intent1 = new Intent(getActivity(), UsedCheckActivity.class);
                if (bean != null) {
                    intent1.putExtra("id", receivablesUserId);
                    intent1.putExtra("bean", bean);
                }
                startActivity(intent1);
            }
        });
        commitPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitPay();
            }
        });
        String status;
        if (isReward) {
            status = "打赏";
        } else {
            status = "里程费,维修费,保养费,配件,二手机评估,打赏,其他(详细备注)";
        }
        String[] arr = status.split(",");
        for (int i = 0; i < arr.length; i++) {
            View view = View.inflate(getContext(), R.layout.item_pay_purpose, null);
            final TextView textView = (TextView) view.findViewById(R.id.item);
            final TextView index = (TextView) view.findViewById(R.id.type);
            index.setText(String.valueOf(i));
            textView.setText(arr[i]);

            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = 5;
            lp.rightMargin = 5;
            lp.topMargin = 5;
            lp.bottomMargin = 5;
            if (isReward) {
                if (arr[i].equals("打赏")) {
                    textView.setSelected(true);
                    typeSet.add(textView.getText().toString());
                }
            } else {
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (textView.isSelected()) {
                            textView.setSelected(false);
                            if (textView.getText().toString().equals("其他(详细备注)"))
                                otherRemarks = false;
                            typeSet.remove(textView.getText().toString());
                        } else {
                            textView.setSelected(true);
                            if (textView.getText().toString().equals("其他(详细备注)"))
                                otherRemarks = true;
                            typeSet.add(textView.getText().toString());
                        }
                    }
                });
            }
            payPurposes.addView(view, lp);
        }

        adapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_fast_pay_rv, parent, false),
                        new BaseViewHolder.Callbacks2() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                if (data instanceof RewardBean) {
                                    RewardBean bean = (RewardBean) data;
                                    holder.setText(R.id.userName, bean.getUserName()+"打赏了");
                                    holder.setText(R.id.money, bean.getMoney()+"元");
                                    ImageView userHead = holder.getView(R.id.userHead);
                                    ImageDisplayUtil.LoadCircleImg( getActivity(), bean.getUserPic(),userHead);
                                }
                            }

                            @Override
                            public void onItemClick(BaseViewHolder holder, View view, int position) {
                            }
                        });
                return holder;
            }

        };
    }

    private void commitPay() {
        String money = payNumber.getText().toString();
        if (TextUtils.isEmpty(money)) {
            showTost("请输入支付金额", 0);
            return;
        }
        if (Double.valueOf(money) < 1) {
            showTost("最小金额为1元", 0);
            return;
        }
        String other = etPurposes.getText().toString();
        if (otherRemarks) {
            if (TextUtils.isEmpty(other)) {
                showTost("请输入其他详情备注", 0);
                return;
            }
        }

        if (!cbLaw.isChecked()) {
            showTost("请勾选免责声明", 0);
            return;
        }
        double mMoney = Double.valueOf(money);
        Intent intent = new Intent(getActivity(), PayActivity.class);
        if (isReward) {
            intent.putExtra("type", 3);
        } else {
            intent.putExtra("type", 5);
            String purpose = "";
            for (String s : typeSet) {
                purpose += s + " ";
            }
            if (!otherRemarks) {
                if (TextUtils.isEmpty(purpose)) {
                    showTost("请输入或者选择费用用途", 0);
                    return;
                }
            }
            intent.putExtra("purpose", purpose + other);
            Log.e("purpose+ other", purpose + other);
        }

        intent.putExtra("eg_user_id", receivablesUserId);
        intent.putExtra("money", mMoney);
        intent.putExtra("name", receivablesName.getText().toString());
        intent.putExtra("eg_pic", receivablesHeadUrl);
        startActivity(intent);
    }

    private LawVO mMZ;

    @Override
    public void loadData() {
        getXieyi();
        if(isReward){
            selProjectorRewardList();
        }
    }

    private void getXieyi() {
        if (MyApplication.userIdIsEmpty(getContext()))
            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
//        Call<ApiResponseBody<UserInfoVO>> call = apiservice.getUserInfo(params);
//        call.enqueue(new Callback<ApiResponseBody<UserInfoVO>>() {
//            @Override
//            public void onResponse(Call<ApiResponseBody<UserInfoVO>> call, Response<ApiResponseBody<UserInfoVO>> response) {
//                if (response.isSuccessful()) {
//                    UserInfoVO mUserInfo = response.body().getResult();
//                    payName.setText(mUserInfo.getUsername());
//                    payPhone.setText(String.valueOf(mUserInfo.getPhone()));
//                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, mUserInfo.getUserPic());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponseBody<UserInfoVO>> call, Throwable t) {
//                ApiException apiException = ExceptionHandle.handleException(t);
//                if (apiException.isTokenInvalid()) {
////                    showUnLoginSnackbar();
//                } else if (apiException.isNetConnected()) {
//                    showSetNetworkSnackbar();
//                } else {
////                    showTost(apiException.getMessage(), 0);
//                }
//            }
//        });
        if (isReward)
            params.put("type", 10);
        else
            params.put("type", 11);
        final Call<ApiResponseBody<LawVO>> law1 = apiservice.xieyiInfo(params);
        law1.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                if (response.isSuccessful()) {
                    mMZ = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {

            }
        });

    }

    //打赏列表
    public void selProjectorRewardList() {
        showProgress(getClass().getSimpleName());
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("eguserId",receivablesUserId);
        Call<ApiResponseBody<List<RewardBean>>> call = apiservice.selProjectorRewardList(params);
        call.enqueue(new Callback<ApiResponseBody<List<RewardBean>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<RewardBean>>> call, Response<ApiResponseBody<List<RewardBean>>> response) {
                if (response.isSuccessful()) {
                    List<RewardBean> datas = response.body().getResult();
                    if (datas != null) {
                        if(datas.size()>0){
                            adapter.setData(datas);
//                            rvPayUser.setNestedScrollingEnabled(true);
                            rvPayUser.setAdapter(adapter);
                        }
                    }
                }
                dismissProgress();

            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<RewardBean>>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void a(PayFinishEvent b) {
        if (b.getType()) {
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }
}
